import os
import requests

from flask import request, jsonify
from watchlist import app, db
from watchlist.models import Message_History, User, Log_History
from watchlist.utils import tools
from openai import OpenAI
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from datetime import timedelta
from sqlalchemy import func

client = OpenAI(
    api_key = os.environ.get("OPENAI_API_KEY"),
)

@app.route('/messageHistory', methods=['POST'])
@jwt_required()
def messageHistory():
    userId = get_jwt_identity()
     # 获取 JSON 数据
    data = request.json
    # 从 JSON 数据中获取 'page' 参数，默认值为 1
    page = data.get('page', 1)
    per_page = 10  # 每页显示的数量
    # 条件查询并排序
    query = Message_History.query.filter(Message_History.user_id == userId).order_by(Message_History.id.desc())

    # 计算查询范围
    messages = query.paginate(page=page, per_page=per_page, error_out=False)
    
    # 将查询结果转换为可序列化的数据结构
    message_list = [
        {
            "id": message.id,
            "content": message.content,
            "userType": message.user_type,
            "name": 'You' if message.user_type == 'user' else 'ChatGPT'
        }
        for message in messages.items
    ]

    data = {
        "list": message_list,
        "totalPages": messages.pages,
        "totalCount": messages.total,
    }

    # 返回处理后的数据作为JSON响应
    return jsonify({"result": data})

@app.route('/sendMessage', methods=['POST'])
@jwt_required()
def sendMessage(): 
    userId = get_jwt_identity()
    # 获取POST请求的数据
    userData = request.get_json()
    print('接收到参数:', userData)

    # 查询出最近10条记录作为上下文
    message_list = Message_History.query.filter(Message_History.user_id == userId).order_by(Message_History.id.desc()).limit(10)
     # 查询出最近10条记录token数量
    tokenCount = db.session.query(Message_History.user_id, func.sum(Message_History.total_tokens).label('total_tokens_sum')).filter(Message_History.user_id == userId).group_by(Message_History.user_id).first()
    if tokenCount is not None:
        print('tokenCount:', tokenCount[1])
    # 将查询结果转换为可序列化的数据结构
    messages = [
        {
            "role": message.user_type,
            "content": message.content,
        }
        for message in message_list
    ]
    messages=messages[::-1]
    messages.append({
        "role": 'user',
        "content": userData['content'],
    })
    print('messages', str(messages))
    result = standardDeepseek(str(userId), messages)
    # 保存用户消息
    current_time = tools.getNowTime()
    userMessage = Message_History(user_id=userId, user_type='user', content=userData['content'], total_tokens=0, create_time=current_time)
    db.session.add(userMessage)
    aiMessage = Message_History(user_id=userId, user_type='assistant', content=result['content'], total_tokens=result['totalTokens'], create_time=current_time)
    db.session.add(aiMessage)
    db.session.commit()
    # 将 aiMessage 对象处理为 JSON 字典
    ai_message_dict = {
        "id": aiMessage.id,
        "user_id": aiMessage.user_id,
        "user_type": aiMessage.user_type,
        "content": aiMessage.content,
        "name": 'Deepseek'
    }
    # 返回处理后的数据作为JSON响应
    return jsonify({"result": ai_message_dict})


@app.route('/sendMessageChatGPT', methods=['POST'])
@jwt_required()
def sendMessageChatGPT(): 
    userId = get_jwt_identity()
    # 获取POST请求的数据
    userData = request.get_json()
    print('接收到参数:', userData)

    # 查询出最近10条记录作为上下文
    message_list = Message_History.query.filter(Message_History.user_id == userId).order_by(Message_History.id.desc()).limit(10)
     # 查询出最近10条记录token数量
    tokenCount = db.session.query(Message_History.user_id, func.sum(Message_History.total_tokens).label('total_tokens_sum')).filter(Message_History.user_id == userId).group_by(Message_History.user_id).first()
    if tokenCount is not None:
        print('tokenCount:', tokenCount[1])
    # 将查询结果转换为可序列化的数据结构
    messages = [
        {
            "role": message.user_type,
            "content": message.content,
        }
        for message in message_list
    ]
    messages=messages[::-1]
    messages.append({
        "role": 'user',
        "content": userData['content'],
    })
    print('messages', str(messages))
    result = standard(str(userId), messages)
    # 保存用户消息
    current_time = tools.getNowTime()
    userMessage = Message_History(user_id=userId, user_type='user', content=userData['content'], total_tokens=0, create_time=current_time)
    db.session.add(userMessage)
    aiMessage = Message_History(user_id=userId, user_type='assistant', content=result['content'], total_tokens=result['totalTokens'], create_time=current_time)
    db.session.add(aiMessage)
    db.session.commit()
    # 将 aiMessage 对象处理为 JSON 字典
    ai_message_dict = {
        "id": aiMessage.id,
        "user_id": aiMessage.user_id,
        "user_type": aiMessage.user_type,
        "content": aiMessage.content,
        "name": 'ChatGPT'
    }
    # 返回处理后的数据作为JSON响应
    return jsonify({"result": ai_message_dict})


# Deepseek
def standardDeepseek(userId, messages):
        
    # DeepSeek API 的基本信息
    API_URL = os.environ.get("BASE_URL") + '/chat/completions'
    API_KEY = os.environ.get("OPENAI_API_KEY")

    # 请求头，包含 API 密钥
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }

    # 请求体，包含会话内容
    data = {
        "model": "deepseek-chat",  # 使用的模型名称
        "messages": messages,
        "stream": False
    }

    print('请求参数data', str(data))
    print('请求参数API_URL', str(API_URL))
    print('请求参数API_KEY', str(API_KEY))

    # 发送 POST 请求
    response = requests.post(API_URL, headers=headers, json=data)

    # 检查响应状态
    if response.status_code == 200:
        # 解析响应内容
        result = response.json()
        print("请求成功，状态码:", response.status_code)
        print("DeepSeek 的回复:", result["choices"][0]["message"]["content"])
        result = {
            'content': result["choices"][0]["message"]["content"],
            'totalTokens': 0
        }
    else:
        print("请求失败，状态码:", response.status_code)
        print("错误信息:", response.text)
        result = {
            'content': response.text,
            'totalTokens': 0
        }
    return result



# ChatGpt标准单条
def standard(userId, messages):
    # https://platform.openai.com/docs/models/overview
    # gpt-3.5-turbo-1106   6.06s
    # gpt-4 34.78s
    completion = client.chat.completions.create(
        model="gpt-3.5-turbo-1106",
        messages=messages,
        user=userId
    )
    print('原始返回', completion)
    result = {
        'content': completion.choices[0].message.content,
        'totalTokens': completion.usage.total_tokens
    }
    print('请求返回', result)
    return result

@app.route('/login', methods=['POST'])
def login():
    app.logger.info(request.get_data(as_text=True))
    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400
    username = request.json.get('username', None)
    password = request.json.get('password', None)
    if not username or not password:
        return jsonify({"msg": "缺少用户名或密码"}), 400
    
    user = User.query.filter_by(username=username).first()
    # 验证用户名和密码是否一致
    if user is not None and username == user.username and user.validate_password(password):
        access_token = create_access_token(identity=user.id, expires_delta=timedelta(hours=2))
        client_ip = request.remote_addr
        print(client_ip)
        logHistory = Log_History(user_id=user.id, log_msg='用户登录,地址:' + client_ip, create_time=tools.getNowTime())
        db.session.add(logHistory)
        db.session.commit()
        return jsonify({"result": access_token }), 200
    return jsonify({"msg": "用户名或密码无效"}), 401 # 验证失败，显示错误消息

@app.route('/register', methods=['POST'])
def register():
    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400
    username = request.json.get('username', None)
    password = request.json.get('password', None)
    code = request.json.get('code', None)
    if not code or code != '889966':
        return jsonify({"msg": "无效的邀请码"}), 400 
    if not username or not password:
        return jsonify({"msg": "缺少用户名或密码"}), 400    
    
    user = User.query.filter_by(username=username).first()
    # 验证用户名是否存在
    if user is not None:
        return jsonify({"msg": "用户名已存在"}), 400
    user = User(username=username, user_role='user', create_time=tools.getNowTime(), del_flag=0)
    user.set_password(password)  # 设置密码
    db.session.add(user)
    db.session.commit()
    access_token = create_access_token(identity=user.id, expires_delta=timedelta(hours=2))
    return jsonify({"result": access_token }), 200